package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysUserSocial;
import org.dromara.system.domain.bo.SysUserSocialBo;
import org.dromara.system.domain.vo.SysUserSocialVo;
import org.dromara.system.mapper.SysUserSocialMapper;
import org.dromara.system.service.ISysUserSocialService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 社交关联Service业务层处理
 *
 * @author Denny
 * @date 2025-10-22
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserSocialServiceImpl implements ISysUserSocialService {

    private final SysUserSocialMapper baseMapper;

    @Override
    @Cacheable(cacheNames = CacheNames.SYS_USER_USERID_SOCIAL, key = "#userId + '#' + #type", condition = "#userId != null and #type != null", unless = "#result == null")
    public SysUserSocial queryByUserId(Long userId, Integer type) {
        LambdaQueryWrapper<SysUserSocial> lwq = Wrappers.lambdaQuery(SysUserSocial.class).eq(SysUserSocial::getUserId, userId)
            .eq(SysUserSocial::getType, type);
        return baseMapper.selectOne(lwq);
    }

    /**
     * unionId 直查 登录时候使用可以判断是否在公众号/小程序谁先注册了避免重复注册
     * @param unionId unionId
     * @param type   类型
     * @return
     */
    @Override
    @Cacheable(cacheNames = CacheNames.SYS_USER_UNIONID_SOCIAL, key = "#unionId + '#' + #type", condition = "#unionId != null and #type != null", unless = "#result == null")
    public SysUserSocial queryByUnionId(String unionId, Integer type) {
        LambdaQueryWrapper<SysUserSocial> lwq = Wrappers.lambdaQuery(SysUserSocial.class).eq(SysUserSocial::getUnionId, unionId)
            .eq(SysUserSocial::getType, type);
        return baseMapper.selectOne(lwq);
    }

    /**
     * 根据类型和 openId查询用户
     *
     * @param openId 社交账号openId
     * @param type   社交类型
     * @return 社交关联
     */
    @Cacheable(cacheNames = CacheNames.SYS_USER_OPENID_SOCIAL, key = "#openId + '#' + #type", condition = "#openId != null and #type != null", unless = "#result == null")
    @Override
    public SysUserSocial queryByOpenId(String openId, Integer type) {
        LambdaQueryWrapper<SysUserSocial> lwq = Wrappers.lambdaQuery(SysUserSocial.class).eq(SysUserSocial::getOpenId, openId)
            .eq(SysUserSocial::getType, type);
        return baseMapper.selectOne(lwq);
    }

    /**
     * 查询社交关联
     *
     * @param id 主键
     * @return 社交关联
     */
    @Override
    public SysUserSocialVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询社交关联列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 社交关联分页列表
     */
    @Override
    public TableDataInfo<SysUserSocialVo> queryPageList(SysUserSocialBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserSocial> lqw = buildQueryWrapper(bo);
        Page<SysUserSocialVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的社交关联列表
     *
     * @param bo 查询条件
     * @return 社交关联列表
     */
    @Override
    public List<SysUserSocialVo> queryList(SysUserSocialBo bo) {
        LambdaQueryWrapper<SysUserSocial> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserSocial> buildQueryWrapper(SysUserSocialBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserSocial> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserSocial::getId);
        lqw.eq(bo.getType() != null, SysUserSocial::getType, bo.getType());
        lqw.eq(bo.getUserId() != null, SysUserSocial::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), SysUserSocial::getOpenId, bo.getOpenId());
        return lqw;
    }

    /**
     * 新增社交关联
     *
     * @param bo 社交关联
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysUserSocialBo bo) {
        SysUserSocial add = MapstructUtils.convert(bo, SysUserSocial.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改社交关联
     *
     * @param bo 社交关联
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysUserSocialBo bo) {
        SysUserSocial update = MapstructUtils.convert(bo, SysUserSocial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserSocial entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除社交关联信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
